<template>
  <div>
    <van-uploader @oversize="onOversize" :max-size="500 * 1024" v-model="fileList" :max-count="1"
      :after-read="afterRead" />
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { showToast } from 'vant';
import axios from 'axios';
const emit = defineEmits(['upload-success', 'upload-error']);
const fileList = ref([]);

const props = defineProps({
  name: {
    type: String,
    default: 'file'
  },
  defaultUrl: {
    type: String,
    default: ''
  }
});


watch(() => props.defaultUrl,(newUrl) => {
    if (newUrl) {
      fileList.value = [{
        url: newUrl
      }];
    }
  }
);

const onOversize = () => {
  showToast('文件大小不能超过 5MB');
};
const afterRead = async (file) => {
  try {
    const formData = new FormData();
    formData.append('file', file?.file);
    const res = await axios.post('/api/files/upload/1', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    if (res?.data.code === 200) {
      emit('upload-success', res?.data?.data);
      showToast('上传成功');
    }
    else {
      throw new Error('上传失败，未返回文件路径');
    }
  } catch (error) {
    emit('upload-error', error);
    showToast('上传失败');
  }


};
</script>

<style lang="less" scoped></style>
